package com.apesource.project02.service;

import com.alibaba.fastjson.JSON;
import com.apesource.project02.mapper.IMarathonEventsMapper;
import com.apesource.project02.pojo.MarathonEvent;
import com.apesource.project02.util.ResponseEntity;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @version 1.0
 * @auther:暮雪
 * @date:2025/9/18
 */

@Service
public class MarathonEventServletImp extends ServiceImpl<IMarathonEventsMapper, MarathonEvent> implements IMarathonEventService {
    @Autowired
    private IMarathonEventsMapper marathonEventsMapper;
    @Autowired
    private RedisTemplate jsonRedisTemplate;

    @Override
    public ResponseEntity<MarathonEvent> getMarathonEventById(int id) {
        ResponseEntity<MarathonEvent> eventsResponseEntity = new ResponseEntity<>();
        Object jsonObj= jsonRedisTemplate.opsForValue().get("marathonEvent:id:"+id);
        MarathonEvent marathonEvent;
        if (jsonObj != null) {
            marathonEvent = JSON.parseObject(jsonObj.toString(), MarathonEvent.class);
        } else {
            marathonEvent = marathonEventsMapper.selectById(id);
            if (marathonEvent != null)
                jsonRedisTemplate.opsForValue().set("marathonEvent:id:"+id, JSON.toJSONString(marathonEvent));
        }
        eventsResponseEntity.setData(marathonEvent);
        eventsResponseEntity.setStatusCode(marathonEvent != null ? 200 : 404);
        eventsResponseEntity.setMessage(marathonEvent != null ? "OK" : "Not Found");
        return eventsResponseEntity;

    }

    @Override
    public ResponseEntity<List<MarathonEvent>> getMarathonEvents() {
        ResponseEntity<List<MarathonEvent>> eventsResponseEntity = new ResponseEntity<>();
        Set<String> keys = jsonRedisTemplate.keys("marathonEvent:id:*");
        List<MarathonEvent> marathonEvents = new ArrayList<>();
        MarathonEvent marathonEvent;
        if(keys != null && !keys.isEmpty()){
            for (String key : keys) {
                Object jsonObj = jsonRedisTemplate.opsForValue().get(key);
                marathonEvent = JSON.parseObject(jsonObj.toString(), MarathonEvent.class);
                if (marathonEvent != null) marathonEvents.add(marathonEvent);
            }
        }else {
            marathonEvents = marathonEventsMapper.selectList(null);
            for (MarathonEvent event : marathonEvents) {
                jsonRedisTemplate.opsForValue().set("marathonEvent:id:"+event.getEventId(), JSON.toJSONString(event));
            }
        }
        eventsResponseEntity.setData(marathonEvents);
        eventsResponseEntity.setStatusCode(200);
        eventsResponseEntity.setMessage("success");
        return eventsResponseEntity;
    }

    @Override
    public ResponseEntity<List<MarathonEvent>> getMarathonEventsByDate() {
        ResponseEntity<List<MarathonEvent>> eventsResponseEntity = new ResponseEntity<>();
        Set<String> keys = jsonRedisTemplate.keys("marathonEvent:id:*");
        List<MarathonEvent> marathonEvents = new ArrayList<>();
        MarathonEvent marathonEvent;
        if(keys != null && !keys.isEmpty()){
            for (String key : keys) {
                Object jsonObj = jsonRedisTemplate.opsForValue().get(key);
                marathonEvent = JSON.parseObject(jsonObj.toString(), MarathonEvent.class);
                if (marathonEvent != null) marathonEvents.add(marathonEvent);
            }
        }else {
            marathonEvents = marathonEventsMapper.selectList(null);
            for (MarathonEvent event : marathonEvents) {
                jsonRedisTemplate.opsForValue().set("marathonEvent:id:"+event.getEventId(), JSON.toJSONString(event));
            }
        }
        // 关键修复：接收filter返回的新流，再执行collect（终端操作）
        List<MarathonEvent> filteredEvents = marathonEvents.stream()
                .filter(mEvent -> {
                    // 额外判空：避免mEvent或endTime为null导致空指针
                    return mEvent != null && mEvent.getStartTime() != null
                            && mEvent.getStartTime().after(new Date());
                })
                .collect(Collectors.toList()); // 对新流执行终端操作，避免原流重复消费
        eventsResponseEntity.setData(filteredEvents);
        eventsResponseEntity.setStatusCode(200);
        eventsResponseEntity.setMessage("success");
        return eventsResponseEntity;

    }
}
